package com.stox.client.ui.javafx.chartingy.model.node;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.paint.Color;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;

import com.stox.client.ui.javafx.chartingy.model.plot.Data;
import com.stox.client.ui.javafx.chartingy.model.plot.Plot;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;
import com.stox.shared.indicator.model.StochasticValue;

public class StochasticPlotNode<T> extends PlotNode<T, StochasticValue> {

	private final Path kPath = UI.style(new Path(),CSS.kPlotNode);
	private final Path dPath = UI.style(new Path(),CSS.dPlotNode);
	private final Plot<T, StochasticValue> plot;
	
	public StochasticPlotNode(final Plot<T, StochasticValue> plot) {
		this.plot = plot;
		getChildren().addAll(kPath, dPath);
		UI.style(kPath, CSS.plotNode, CSS.stochasticPlotNode);
		dPath.setStrokeWidth(1);
		updateColor();
		plot.colorProperty().addListener(new ChangeListener<Color>() {
			@Override
			public void changed(final ObservableValue<? extends Color> observable, final Color oldValue, final Color newValue) {
				updateColor();
			}
		});
		updateColor();
	}
	
	public void updateColor() {
		final String color = UI.web(plot.getColor());
		kPath.setStyle("-fx-plot-node-color:" + color + "");
		dPath.setStroke(plot.getColor().invert());
	}

	@Override
	public void preLayout() {
		kPath.getElements().clear();
		dPath.getElements().clear();
	}

	@Override
	public void layout(final Data<T, StochasticValue> data, final double x, final double unitWidth) {
		double y = getDisplayPosition(data.getExtraValue().getK());
		if (kPath.getElements().isEmpty()) {
			kPath.getElements().add(new MoveTo(x, y));
		} else {
			kPath.getElements().add(new LineTo(x, y));
		}
		
		Double d = data.getExtraValue().getD();
		if(null != d){
			y = getDisplayPosition(d);
			if(dPath.getElements().isEmpty()){
				dPath.getElements().add(new MoveTo(x,y));
			}else{
				dPath.getElements().add(new LineTo(x,y));
			}
		}
	}

	@Override
	public void postLayout() {

	}

	@Override
	public Plot<T, StochasticValue> getPlot() {
		return plot;
	}

}
